package com.cy.pj.goods.controller;

import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@Slf4j
@RequestMapping("/goods")
public class Goodscontroller {
    @Autowired
    private GoodsService goodsService;
//    @ExceptionHandler(RuntimeException.class)
//    @ResponseBody
//    public String doHandleRuntimeException(RuntimeException e){
//        log.error("exception{}",e.getMessage());
//        return e.getMessage();
//    }
    @PostMapping("/doUpdateGoods")
    public String doUpdateGoods(Goods goods,Model model){
        goodsService.updateGoods(goods);
//        List<Goods> list=goodsService.findGoods(null);
//        model.addAttribute("list",list);
//        return "goods";
        return "redirect:/goods/doFindGoods";
    }
//    @RequestMapping("/doErrorUI")
//    public String doErrorUI(){
//        return "error";
//    }
    @RequestMapping("/doFindById/{id}")
    public String  doFindById(@PathVariable Integer id, Model model){
        Goods goods=goods = goodsService.findById(id);
        model.addAttribute("goods",goods);
        return "goods-update";
    }
    @PostMapping("/doSaveGoods")
    public String doSaveGoods(Goods goods,Model model){
       goodsService.saveGoods(goods);
//        List<Goods> list=goodsService.findGoods(null);
//        model.addAttribute("list",list);
//        return "goods";
        return "redirect:/goods/doFindGoods";
    }
    @GetMapping("/doGoodsAddUI")
    public String doGoodsAddUI(){
        return "goods-add";
    }
    @RequestMapping("/doDeleteById")
    public String doDeleteById(Integer id,Model model){
        goodsService.deleteById(id);
        List<Goods> list=goodsService.findGoods(null);
        model.addAttribute("list",list);
        return "goods";
    }
    @GetMapping("doFindXRGoods")
    @ResponseBody
    public XResult doFindXRGoods(String name){
        List<Goods> list=goodsService.findGoods(name);
        return new XResult(list);
    }
    @GetMapping("/doFindGoods")
    public String doFindGoods(Model model,String name){
        List<Goods> list=goodsService.findGoods(name);
//        for (Goods g:list) {
//            System.out.println(g);
//        }
        model.addAttribute("list",list);
        return "goods";
    }
}
